package com.example.remotecontrol.ui.remote

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material.icons.filled.Devices
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowLeft
import androidx.compose.material.icons.filled.KeyboardArrowRight
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Power
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.Source
import androidx.compose.material.icons.filled.VolumeDown
import androidx.compose.material.icons.filled.VolumeMute
import androidx.compose.material.icons.filled.VolumeUp
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ElevatedButton
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.remotecontrol.R
import com.example.remotecontrol.data.model.Device
import com.example.remotecontrol.data.model.TVBrand
import com.example.remotecontrol.data.model.TVRemoteKey

/**
 * 遥控器主界面
 */
@Composable
fun RemoteScreen(
    viewModel: RemoteViewModel = hiltViewModel()
) {
    val selectedDevice by viewModel.selectedDevice.collectAsState()
    val recentDevices by viewModel.recentDevices.collectAsState()
    val irAvailable by viewModel.irAvailable.collectAsState()
    val commandStatus by viewModel.commandStatus.collectAsState()
    
    val snackbarHostState = remember { SnackbarHostState() }
    
    // 处理命令状态变更
    LaunchedEffect(commandStatus) {
        when (commandStatus) {
            is CommandStatus.Error -> {
                snackbarHostState.showSnackbar((commandStatus as CommandStatus.Error).message)
                viewModel.clearCommandStatus()
            }
            else -> { /* 其他状态不显示Snackbar */ }
        }
    }
    
    Scaffold(
        topBar = { 
            TopAppBar(
                title = { Text(stringResource(R.string.nav_remote)) },
                actions = {
                    IconButton(onClick = { /* 打开设置 */ }) {
                        Icon(Icons.Default.Settings, contentDescription = "设置")
                    }
                }
            )
        },
        snackbarHost = { SnackbarHost(snackbarHostState) }
    ) { padding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
                .verticalScroll(rememberScrollState())
        ) {
            // 设备选择栏
            DeviceSelectionBar(
                selectedDevice = selectedDevice,
                recentDevices = recentDevices,
                onDeviceSelected = { viewModel.selectDevice(it) },
                onAddDeviceClicked = { /* 跳转到添加设备界面 */ }
            )
            
            // 红外遥控器UI
            RemoteControlPanel(
                isIrAvailable = irAvailable,
                deviceName = selectedDevice?.name ?: "通用遥控器",
                onCommandClicked = { command ->
                    viewModel.sendGenericTVCommand(command)
                }
            )
        }
    }
}

/**
 * 设备选择栏
 */
@Composable
fun DeviceSelectionBar(
    selectedDevice: Device?,
    recentDevices: List<Device>,
    onDeviceSelected: (Device) -> Unit,
    onAddDeviceClicked: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Icon(
                    imageVector = Icons.Default.Devices,
                    contentDescription = null,
                    tint = MaterialTheme.colorScheme.primary
                )
                
                Spacer(modifier = Modifier.width(8.dp))
                
                Text(
                    text = selectedDevice?.name ?: "选择设备",
                    style = MaterialTheme.typography.titleMedium
                )
                
                Spacer(modifier = Modifier.weight(1f))
                
                IconButton(onClick = onAddDeviceClicked) {
                    Icon(
                        imageVector = Icons.Default.Add,
                        contentDescription = "添加设备",
                        tint = MaterialTheme.colorScheme.primary
                    )
                }
            }
            
            Spacer(modifier = Modifier.height(8.dp))
            
            if (recentDevices.isEmpty()) {
                Text(
                    text = "没有最近使用的设备",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            } else {
                LazyRow(
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    contentPadding = PaddingValues(horizontal = 4.dp)
                ) {
                    items(recentDevices) { device ->
                        DeviceChip(
                            device = device,
                            isSelected = device.id == selectedDevice?.id,
                            onClick = { onDeviceSelected(device) }
                        )
                    }
                }
            }
        }
    }
}

/**
 * 设备选择芯片
 */
@Composable
fun DeviceChip(
    device: Device,
    isSelected: Boolean,
    onClick: () -> Unit
) {
    ElevatedButton(
        onClick = onClick,
        modifier = Modifier.height(40.dp),
        contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp)
    ) {
        Text(
            text = device.name,
            style = MaterialTheme.typography.labelMedium,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
    }
}

/**
 * 遥控器面板
 */
@Composable
fun RemoteControlPanel(
    isIrAvailable: Boolean,
    deviceName: String,
    onCommandClicked: (String) -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // 设备名称和状态
            Text(
                text = deviceName,
                style = MaterialTheme.typography.titleLarge,
                textAlign = TextAlign.Center
            )
            
            if (!isIrAvailable) {
                Text(
                    text = stringResource(R.string.error_ir_not_supported),
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.error,
                    textAlign = TextAlign.Center,
                    modifier = Modifier.padding(top = 8.dp)
                )
            }
            
            Spacer(modifier = Modifier.height(24.dp))
            
            // 电源按钮
            RemoteButton(
                icon = Icons.Default.Power,
                text = stringResource(R.string.power),
                onClick = { onCommandClicked("POWER") },
                modifier = Modifier.size(64.dp),
                enabled = isIrAvailable
            )
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 输入源和菜单按钮
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                RemoteButton(
                    icon = Icons.Default.Source,
                    text = "信号源",
                    onClick = { onCommandClicked("SOURCE") },
                    enabled = isIrAvailable
                )
                
                RemoteButton(
                    icon = Icons.Default.Home,
                    text = stringResource(R.string.home),
                    onClick = { onCommandClicked("HOME") },
                    enabled = isIrAvailable
                )
                
                RemoteButton(
                    icon = Icons.Default.Menu,
                    text = stringResource(R.string.menu),
                    onClick = { onCommandClicked("MENU") },
                    enabled = isIrAvailable
                )
            }
            
            Spacer(modifier = Modifier.height(24.dp))
            
            // 方向导航按钮
            DirectionPad(
                onUpClicked = { onCommandClicked("UP") },
                onDownClicked = { onCommandClicked("DOWN") },
                onLeftClicked = { onCommandClicked("LEFT") },
                onRightClicked = { onCommandClicked("RIGHT") },
                onCenterClicked = { onCommandClicked("OK") },
                enabled = isIrAvailable
            )
            
            Spacer(modifier = Modifier.height(24.dp))
            
            // 返回按钮
            RemoteButton(
                text = stringResource(R.string.back),
                onClick = { onCommandClicked("RETURN") },
                enabled = isIrAvailable
            )
            
            Spacer(modifier = Modifier.height(24.dp))
            
            // 音量和频道控制
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                // 音量控制
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    RemoteButton(
                        icon = Icons.Default.VolumeUp,
                        onClick = { onCommandClicked("VOLUME_UP") },
                        enabled = isIrAvailable
                    )
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    
                    RemoteButton(
                        icon = Icons.Default.VolumeMute,
                        onClick = { onCommandClicked("MUTE") },
                        enabled = isIrAvailable
                    )
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    
                    RemoteButton(
                        icon = Icons.Default.VolumeDown,
                        onClick = { onCommandClicked("VOLUME_DOWN") },
                        enabled = isIrAvailable
                    )
                }
                
                // 频道控制
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    RemoteButton(
                        text = "CH+",
                        onClick = { onCommandClicked("CHANNEL_UP") },
                        enabled = isIrAvailable
                    )
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    
                    RemoteButton(
                        icon = Icons.Default.PlayArrow,
                        onClick = { onCommandClicked("GUIDE") },
                        enabled = isIrAvailable
                    )
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    
                    RemoteButton(
                        text = "CH-",
                        onClick = { onCommandClicked("CHANNEL_DOWN") },
                        enabled = isIrAvailable
                    )
                }
            }
            
            Spacer(modifier = Modifier.height(24.dp))
            
            // 数字按键
            Column(
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                // 第一行: 1 2 3
                Row(
                    horizontalArrangement = Arrangement.spacedBy(16.dp)
                ) {
                    NumberButton(
                        number = "1",
                        onClick = { onCommandClicked("NUMBER_1") },
                        enabled = isIrAvailable
                    )
                    NumberButton(
                        number = "2",
                        onClick = { onCommandClicked("NUMBER_2") },
                        enabled = isIrAvailable
                    )
                    NumberButton(
                        number = "3",
                        onClick = { onCommandClicked("NUMBER_3") },
                        enabled = isIrAvailable
                    )
                }
                
                Spacer(modifier = Modifier.height(16.dp))
                
                // 第二行: 4 5 6
                Row(
                    horizontalArrangement = Arrangement.spacedBy(16.dp)
                ) {
                    NumberButton(
                        number = "4",
                        onClick = { onCommandClicked("NUMBER_4") },
                        enabled = isIrAvailable
                    )
                    NumberButton(
                        number = "5",
                        onClick = { onCommandClicked("NUMBER_5") },
                        enabled = isIrAvailable
                    )
                    NumberButton(
                        number = "6",
                        onClick = { onCommandClicked("NUMBER_6") },
                        enabled = isIrAvailable
                    )
                }
                
                Spacer(modifier = Modifier.height(16.dp))
                
                // 第三行: 7 8 9
                Row(
                    horizontalArrangement = Arrangement.spacedBy(16.dp)
                ) {
                    NumberButton(
                        number = "7",
                        onClick = { onCommandClicked("NUMBER_7") },
                        enabled = isIrAvailable
                    )
                    NumberButton(
                        number = "8",
                        onClick = { onCommandClicked("NUMBER_8") },
                        enabled = isIrAvailable
                    )
                    NumberButton(
                        number = "9",
                        onClick = { onCommandClicked("NUMBER_9") },
                        enabled = isIrAvailable
                    )
                }
                
                Spacer(modifier = Modifier.height(16.dp))
                
                // 第四行: 0
                NumberButton(
                    number = "0",
                    onClick = { onCommandClicked("NUMBER_0") },
                    enabled = isIrAvailable
                )
            }
        }
    }
}

/**
 * 遥控按钮
 */
@Composable
fun RemoteButton(
    icon: ImageVector? = null,
    text: String? = null,
    onClick: () -> Unit,
    modifier: Modifier = Modifier.size(56.dp),
    enabled: Boolean = true
) {
    FilledTonalButton(
        onClick = onClick,
        modifier = modifier,
        shape = CircleShape,
        enabled = enabled
    ) {
        if (icon != null) {
            Icon(
                imageVector = icon,
                contentDescription = text ?: "按钮",
                modifier = Modifier.size(24.dp)
            )
        }
        if (text != null && icon == null) {
            Text(text = text)
        }
    }
}

/**
 * 数字按钮
 */
@Composable
fun NumberButton(
    number: String,
    onClick: () -> Unit,
    enabled: Boolean = true
) {
    FilledTonalButton(
        onClick = onClick,
        modifier = Modifier.size(56.dp),
        shape = CircleShape,
        enabled = enabled
    ) {
        Text(
            text = number,
            style = MaterialTheme.typography.titleLarge
        )
    }
}

/**
 * 方向导航面板
 */
@Composable
fun DirectionPad(
    onUpClicked: () -> Unit,
    onDownClicked: () -> Unit,
    onLeftClicked: () -> Unit,
    onRightClicked: () -> Unit,
    onCenterClicked: () -> Unit,
    enabled: Boolean = true
) {
    Box(
        modifier = Modifier
            .size(200.dp)
            .padding(8.dp)
    ) {
        // 上方向按钮
        RemoteButton(
            icon = Icons.Default.KeyboardArrowUp,
            onClick = onUpClicked,
            modifier = Modifier
                .align(Alignment.TopCenter)
                .size(56.dp),
            enabled = enabled
        )
        
        // 左方向按钮
        RemoteButton(
            icon = Icons.Default.KeyboardArrowLeft,
            onClick = onLeftClicked,
            modifier = Modifier
                .align(Alignment.CenterStart)
                .size(56.dp),
            enabled = enabled
        )
        
        // 确认按钮
        RemoteButton(
            text = "OK",
            onClick = onCenterClicked,
            modifier = Modifier
                .align(Alignment.Center)
                .size(64.dp),
            enabled = enabled
        )
        
        // 右方向按钮
        RemoteButton(
            icon = Icons.Default.KeyboardArrowRight,
            onClick = onRightClicked,
            modifier = Modifier
                .align(Alignment.CenterEnd)
                .size(56.dp),
            enabled = enabled
        )
        
        // 下方向按钮
        RemoteButton(
            icon = Icons.Default.KeyboardArrowDown,
            onClick = onDownClicked,
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .size(56.dp),
            enabled = enabled
        )
    }
} 